<?php

namespace Modules\Chip\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use ThrowException;


class ChipAsset extends Model
{

    protected $guarded = [];
    protected $table = 'chip_assets';

    static public $resourceName = '碎片资产';

    protected $casts = [
    ];

    public function records()
    {
        return $this->hasMany('\Modules\Chip\Entities\ChipAssetRecord', 'asset_id');
    }

    protected function change($type, $value, $options)
    {
        if ($type === 0 && $this->balance < $value)
            return false;

        $before = $this->balance ?: 0;

        $this->balance += $value * ($type === 0 ? -1 : 1);;

        $this->save();

        $after = $this->balance;

        $desc = @$options['description'];

        $this->records()->create([
            'uuid' => uniqid(),
            'order_id' => @($options['order_id']),
            'user_id' => $this->user_id,
            'chip_id' => $this->chip_id,
            'before' => $before,
            'after' => $after,
            'value' => $value,
            'type' => $type,
            'description' => $desc
        ]);

        return true;
    }

    public function in($value, $options = [])
    {
        return $this->change(1, $value, $options);
    }

    public function out($value,  $options = [])
    {
        return $this->change(0, $value, $options);
    }
}
